using AutoMapper;
using BaseData.Domain;
using BaseData.ReadApi.Appcontext.Command.EweHistoryRecord_Files;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.ReadApi.Appcontext.CommandHandler.EweHistoryRecord_Files
{
    /// <summary>
    /// 获取种母历史记录分页列表命令处理器
    /// </summary>
    public class GetEweHistoryRecordListCommandHandler : IRequestHandler<GetEweHistoryRecordListCommand, ApiResult<ApiPaging<EweHistoryRecordDto>>>
    {
        private readonly IBaseRepository<EweHistoryRecord> _eweHistoryRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetEweHistoryRecordListCommandHandler> _logger;

        public GetEweHistoryRecordListCommandHandler(
            IBaseRepository<EweHistoryRecord> eweHistoryRecordRepository,
            IMapper mapper,
            ILogger<GetEweHistoryRecordListCommandHandler> logger)
        {
            _eweHistoryRecordRepository = eweHistoryRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取种母历史记录分页列表命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiResult<ApiPaging<EweHistoryRecordDto>>> Handle(GetEweHistoryRecordListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("获取种母历史记录分页列表请求参数为空");
                    return new ApiResult<ApiPaging<EweHistoryRecordDto>> { Code = ApiEnum.查询失败, Message = "请求参数不能为空", data = null };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"获取种母历史记录分页列表数据验证失败: {errorMessage}");
                    return new ApiResult<ApiPaging<EweHistoryRecordDto>> { Code = ApiEnum.查询失败, Message = errorMessage, data = null };
                }

                // 构建查询
                var query = _eweHistoryRecordRepository.GetAll()
                    .Where(e => !e.IsDeleted); // 只查询未删除的记录

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 获取分页数据
                var list = await query
                    .OrderByDescending(e => e.HistoryId) // 按历史记录ID倒序排列
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(e => new EweHistoryRecordDto
                    {
                        HistoryId = e.HistoryId,
                        EweId = e.EweId,
                        MatingDate = e.MatingDate,
                        RamId = e.RamId,
                        PregnancyCheckDate = e.PregnancyCheckDate,
                        PregnancyResult = e.PregnancyResult,
                        DeliveryDate = e.DeliveryDate,
                        HealthyLambCount = e.HealthyLambCount,
                        HealthyLambTotalWeight = e.HealthyLambTotalWeight,
                        WeakLambCount = e.WeakLambCount,
                        DeformedCount = e.DeformedCount,
                        StillbirthCount = e.StillbirthCount,
                        MummyCount = e.MummyCount,
                        AbnormalCount = e.AbnormalCount,
                        CurrentParity = e.CurrentParity,
                        Note = e.Note,

                    })
                    .ToListAsync(cancellationToken);

                // 构建分页结果
                var pagingResult = new ApiPaging<EweHistoryRecordDto>
                {
                    totalCount = totalCount,
                    totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    data = list
                };

                _logger.LogInformation($"成功获取种母历史记录分页列表，第{request.PageIndex}页，共{totalCount}条记录");
                
                return new ApiResult<ApiPaging<EweHistoryRecordDto>>
                {
                    Code = ApiEnum.查询成功,
                    Message = "种母历史记录分页列表获取成功",
                    data = pagingResult
                };
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<ApiPaging<EweHistoryRecordDto>> { Code = ApiEnum.查询失败, Message = ex.Message, data = null };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取种母历史记录分页列表时发生系统异常: {ex.Message}");
                return new ApiResult<ApiPaging<EweHistoryRecordDto>> { Code = ApiEnum.查询失败, Message = "系统异常，请联系管理员", data = null };
            }
        }
    }
}